package jin.si.com.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jin.si.com.entity.User;
import jin.si.com.utils.JsonData;
import org.thymeleaf.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static jin.si.com.service.impl.UserServiceImpl.sessionMap;

/**
 * @description: 过滤器
 * @ClassName TestFilter1
 * @Author MT
 * @Date 2021/5/10 16:07
 **/

@WebFilter(urlPatterns="/order/v1/*",filterName="addOrder")
public class TestFilter1 implements Filter {

    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化===============");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse reps= (HttpServletResponse) servletResponse;
        HttpServletRequest res= (HttpServletRequest) servletRequest;
        String token = res.getHeader("token");

        if(!StringUtils.isEmpty(token)){
            User user = (User) sessionMap.get(token);
            if(user!=null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                JsonData jsonData = JsonData.buildError("登录失败");
                String jsonStr = objectMapper.writeValueAsString(jsonData);
                renderJson(reps,jsonStr);
            }
        }else{
            JsonData jsonData = JsonData.buildError("未登录");
            String jsonStr = objectMapper.writeValueAsString(jsonData);
            renderJson(reps,jsonStr);
        }

    }

    @Override
    public void destroy() {
        System.out.println("销毁===============");
    }

    private void renderJson(HttpServletResponse reps,String jsonStr){
        reps.setCharacterEncoding("UTF-8");
        reps.setContentType("application/json");
        try{
            PrintWriter writer=reps.getWriter();
            writer.write(jsonStr);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }






}
